import React, { useState } from 'react'
import OptionItem from './OptionItem'
import './options.less'
import { QuetionTypeMap } from '@/common'
import { Button, Toast } from 'antd-mobile'
import { submitAnswerAPi } from '@/api'
import { useLocation } from 'react-router-dom'

interface IProp {
    data: QuestionModel
}

export default function Options({ data }: IProp) {
    const optionsArr = JSON.parse(data.optionContent as string) as OptionModel[];
    const { state } = useLocation();

    // 勾选与否的思路：
    // 使用一个数组，把勾选的答案的编号 A/B/C/D 存起来 ，再判断，哪个是在数组里面的，决定， OptionItem 子组件里面的图片是否显示
    const [answers, setAnswers] = useState<string[]>([])

    // 题目的选项被点击的时候的事件
    const change = (key: string) => {
        // 判断当前是 单选还是多选
        if (data.questionType === 'many') {
            // 判断key是否已经在 数组里面，如果在，就是要取消勾选
            if (answers.includes(key)) {
                let idx = answers.findIndex(item => item === key)
                answers.splice(idx, 1)
                setAnswers([...answers])
            } else {
                setAnswers([...answers, key])
            }
        } else {
            // 单选和判断
            setAnswers([key])
        }
    }

    const sureFn = () => {
        let answer = answers.sort().join(',')
        // 判断答案是否正确
        if (answer === data.answer) {
            Toast.show({
                icon: 'success',
                content: '回答正确'
            })
        } else {
            // 提示 - 自己实现
        }
        // 把用户的答案上传到服务器
        submitAnswerAPi({
            categoryCode: data.categoryCode,
            id: data.id,
            userAnswer: answer,
            actionType: 'exam_test', // 是练习模式，还是考试模式
            actionCode: state.actionCode
        }).then(res => {
            if (res.errCode === 0) {
                Toast.show({
                    icon: 'success',
                    content: '提交成功'
                })
            }
        })
    }

    return (
        <div className='options'>
            <div className="title-container">
                <div className='type'>{QuetionTypeMap[data.questionType]}</div>
                <div className='title'>{data.title}</div>
            </div>

            {
                optionsArr?.map(item => <OptionItem onChange={change} isChecked={answers.includes(item.key)} data={item} key={item.key} />)
            }

            <div className='answer'>
                <Button color="primary" fill="outline" onClick={sureFn}>确定</Button>
            </div>
        </div>
    )
}
